#!/usr/bin/env python
# -*- coding: utf-8 -*-

from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, jwt_required, get_jwt_identity

from ...utils.responses import api_success, api_error_response
from ...services.auth_service import AuthService
from ..schemas.auth_schema import LoginSchema, RegisterSchema

# 创建认证蓝图
auth_bp = Blueprint('auth', __name__, url_prefix='/auth')

# 实例化验证模式
login_schema = LoginSchema()
register_schema = RegisterSchema()

# 实例化认证服务
auth_service = AuthService()

@auth_bp.route('/login', methods=['POST'])
def login():
    """用户登录
    
    使用POST+JSON形式接收用户名和密码，返回JWT令牌
    ---
    tags:
      - 认证
    requestBody:
      content:
        application/json:
          schema:
            type: object
            properties:
              username:
                type: string
              password:
                type: string
    responses:
      200:
        description: 登录成功
      401:
        description: 登录失败
    """
    # 验证请求数据必须是JSON
    if not request.is_json:
        return api_error_response("请求必须是JSON格式", 400)
    
    # 加载并验证数据
    try:
        data = login_schema.load(request.json)
    except Exception as e:
        return api_error_response(f"数据验证失败: {str(e)}", 400)
    
    # 尝试登录
    result = auth_service.authenticate(data['username'], data['password'])
    
    if not result['success']:
        return api_error_response(result['message'], 401)
    
    # 创建访问令牌
    access_token = create_access_token(identity=result['user_id'])
    
    return api_success({
        'access_token': access_token,
        'user': result['user']
    }, "登录成功")


@auth_bp.route('/register', methods=['POST'])
def register():
    """用户注册
    
    使用POST+JSON形式接收用户信息进行注册
    """
    # 验证请求数据必须是JSON
    if not request.is_json:
        return api_error_response("请求必须是JSON格式", 400)
    
    # 加载并验证数据
    try:
        data = register_schema.load(request.json)
    except Exception as e:
        return api_error_response(f"数据验证失败: {str(e)}", 400)
    
    # 尝试注册
    result = auth_service.register(data)
    
    if not result['success']:
        return api_error_response(result['message'], 400)
    
    return api_success(result['user'], "注册成功") 